package me.hl;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import me.hl.handler.NettyClientHandler;

/**
 * Created by Planck on 2016/2/25.
 */
public class NettyClient {

    private int port;

    private String host;

    public NettyClient(int port, String host) {
        this.host = host;
        this.port = port;
        start();
    }

    private void start() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.group(eventLoopGroup);
            bootstrap.remoteAddress(host, port);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new NettyClientHandler());
                }
            });

            ChannelFuture future = bootstrap.connect(host,port).sync();
            if(future.isSuccess()){
                SocketChannel socketChannel = (SocketChannel) future.channel();
            }
            //closeFuture  Wait until the connection is closed.
            //close close immediate
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
    public static void main(String[] args) throws InterruptedException {

        NettyClient client = new NettyClient(9999, "localhost");

    }
}
